package com.huanrong.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener
{
    @Override
    public void sessionCreated(HttpSessionEvent e)
    {
        System.out.println("开始会话");
        // 设置session过期时间为10s方便测试
        e.getSession().setMaxInactiveInterval(10);
        ServletContext ctx = e.getSession().getServletContext();
        Integer numSessions = (Integer)ctx.getAttribute("numSessions");
        if (numSessions == null)
        {
            numSessions = new Integer(1);
        }
        else
        {
            int count = numSessions.intValue();
            numSessions = new Integer(count + 1);
        }
        ctx.setAttribute("numSessions", numSessions);
    }
    
    @Override
    public void sessionDestroyed(HttpSessionEvent e)
    {
        System.out.println("结束会话");
        ServletContext ctx = e.getSession().getServletContext();
        Integer numSessions = (Integer)ctx.getAttribute("numSessions");
        if (numSessions == null)
        {
            numSessions = new Integer(0);
        }
        else
        {
            int count = numSessions.intValue();
            numSessions = new Integer(count - 1);
        }
        ctx.setAttribute("numSessions", numSessions);
    }
    
}
